<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/11/19
 * Time: 15:00
 * Created by Created by Panxsoft.
 */

namespace App\Services\Common;

use App\Exceptions\ApiErrCode;
use App\Exceptions\ApiException;
use Illuminate\Support\Facades\Cache;

class VerifyCodeService
{
    const CACHE_KEY_PREFIX = '-';
    const DEFAULT_CACHE_TIME = 5;

    const VERIFY_CODE_REG_TYPE = 'register';

    const VERIFY_CODE_RESET_PWD_TYPE = 'reset-pwd';

    /**
     * 生成验证码
     */
    public function generate()
    {
        return (string) rand(100000, 999999);
    }


    /**
     * 缓存验证码
     * @param $cache_key
     * @param $cache_value
     * @param int $cache_time
     */
    public function cacheVerifyCode($cache_key, $cache_value, $cache_time = self::DEFAULT_CACHE_TIME): void
    {
        Cache::put($cache_key, $cache_value, $cache_time);
    }


    /**
     * 验证 验证码
     * @param string $cache_key
     * @param string $verify_code
     * @throws \Exception
     */
    public function checkVerifyCode(string $cache_key, string $verify_code)
    {
        if (Cache::get($cache_key) === null || $verify_code !== Cache::get($cache_key)) {
            throw new ApiException(ApiErrCode::VERIFY_CODE_FAIL, trans('checker.verification_code_does_not_match'));
        }
    }

    /**
     * 删除已使用的验证码
     * @param $cache_key
     */
    public function destroyUsedVerifyCode($cache_key)
    {
        Cache::forget($cache_key);
    }

    /**
     * 获取注册使用的缓存键
     * @param $unique
     * @param $dial_code
     * @return string
     */
    public function getRegisterCacheKey($unique, $dial_code)
    {
        $cache_key = $unique . VerifyCodeService::CACHE_KEY_PREFIX . VerifyCodeService::VERIFY_CODE_REG_TYPE . $dial_code;

        return $cache_key;
    }

    /**
     * 获取重置密码使用的缓存键
     * @param $unique
     * @param $dial_code
     * @return string
     */
    public function getResetPwdCacheKey($unique, $dial_code)
    {
        $cache_key = $unique . VerifyCodeService::CACHE_KEY_PREFIX . VerifyCodeService::VERIFY_CODE_RESET_PWD_TYPE . $dial_code;

        return $cache_key;
    }
}